/*
 * Copyright 2010 Yaroslav Klymko aka t3hnar
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package ua.t3hnar.io.serializer;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import ua.t3hnar.io.serializer.handlers.FieldHandler;
import ua.t3hnar.io.serializer.handlers.ToInstanceException;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;

/**
 * @author Yaroslav Klymko aka t3hnar
 */
class StreamSplitter extends StreamWorker<InputStream> {
// ------------------------------ FIELDS ------------------------------

    private static final Log LOG = LogFactory.getLog(StreamSplitter.class);

// --------------------------- CONSTRUCTORS ---------------------------

    StreamSplitter(final SerializableFieldOwner owner, final Field field, final FieldHandler handler) {
        super(owner, field, handler);
    }

// -------------------------- OTHER METHODS --------------------------

    @Override
    void work(final InputStream param) throws StreamSerializationException {
        LOG.debug("Working; param: " + param);
        if (param == null) {
            throw new IllegalArgumentException("Param is null");
        }

        final InputStream inputStream = split(param);
        assignToField(inputStream);
    }

    InputStream split(final InputStream inputStream) throws StreamSerializationException {
        LOG.debug("Splitting; inputStream: " + inputStream);
        if (inputStream == null) {
            throw new IllegalArgumentException("InputStream is null");
        }

        final DataInputStream dataInputStream = new DataInputStream(inputStream);
        final int size;
        try {
            size = dataInputStream.readInt();
            final byte[] buffer = new byte[size];
            if (size != 0) {
                dataInputStream.readFully(buffer);
            }
            return new ByteArrayInputStream(buffer);
        } catch (IOException e) {
            final String message = "Failed to read stream: " + e;
            LOG.debug(message, e);
            throw new StreamSerializationException(message, e);
        }
    }

    void assignToField(final InputStream inputStream) throws StreamSerializationException {
        if (inputStream == null) {
            throw new IllegalArgumentException("InputStream is null");
        }

        final Field field = getField();
        final Object instance;
        try {
            instance = getHandler().toInstance(inputStream);
        } catch (ToInstanceException e) {
            final String message = "Failed to getHandler instance: " + e;
            LOG.debug(message);
            throw new StreamSerializationException(message, e);
        }

        final boolean accessible = field.isAccessible();
        field.setAccessible(true);
        try {
            try {
                field.set(getOwner(), instance);
            } catch (IllegalAccessException e) {
                final String message = "Failed to access instance field: " + e;
                LOG.debug(message);
                throw new StreamSerializationException(message, e);
            }
        }
        finally {
            field.setAccessible(accessible);
        }
    }
}
